package com.example.onehourspring.service;

import Converter.StudentConverter;
import com.example.onehourspring.datacess.Student;
import com.example.onehourspring.datacess.StudentRepository;
import com.example.onehourspring.dto.StudentDTO;
import jakarta.transaction.Transactional;
import org.hibernate.mapping.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StudentServiceimp implements StudentService{

    @Autowired
    private StudentRepository studentRepository;
    @Override
    public StudentDTO getStudentById(Long id) {
        Student student = studentRepository.findById(id).orElseThrow(RuntimeException::new);
        return StudentConverter.converterStudent(student);
    }

    //新增方法的实现
    @Override
    public Long addNewStudent(StudentDTO studentDTO) {
        //需要检查邮箱的唯一性，那么就要进studentRepository里卖写findByEmail方法
        List<Student> studentList = studentRepository.findByEmail(studentDTO.getEmail());
        if(!CollectionUtils.isEmpty(studentList)){
            throw new IllegalStateException("email" + studentDTO.getEmail() + "has been taken.");
        }
        //进Converterl里面写转换方法，将studentDTO转换辉student对象，并save到数据库中，返回id
        Student student = studentRepository.save(StudentConverter.converterStudent(studentDTO));
        return student.getId();
    }

    @Override
    public void deleteStudentById(long id) {
        studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id:" + id + "not found"));
        studentRepository.deleteById(id);
    }

    @Override
    @Transactional  //出现错误不会提交
    public StudentDTO updateStudentById(long id, String name, String email) {
        Student studentInDB = studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id:" + id + "not found"));
        if (StringUtils.hasLength(name) && !studentInDB.getName().equals(name)) {
            studentInDB.setName(name);
        }
        if (StringUtils.hasLength(email) && !studentInDB.getEmail().equals(email)){
            studentInDB.setEmail(email);
        }
        Student student = studentRepository.save(studentInDB);
        return StudentConverter.converterStudent(student);
    }
}
